package io.zcoder.innoway.fragments;


import android.app.Activity;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Matrix;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;

import com.afollestad.materialdialogs.DialogAction;
import com.afollestad.materialdialogs.MaterialDialog;
import com.squareup.picasso.Picasso;

import java.io.File;
import java.io.FileOutputStream;
import java.util.Calendar;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import de.hdodenhof.circleimageview.CircleImageView;
import io.zcoder.innoway.R;
import io.zcoder.innoway.activities.InputPassCodeActivity;
import io.zcoder.innoway.utils.Utils;
import io.zcoder.innoway.activities.EditInformationActivity;
import io.zcoder.innoway.activities.FamilyMembersActivity;
import io.zcoder.innoway.activities.ReminderActivity;
import io.zcoder.innoway.activities.SelectBodyTypeActivity;
import io.zcoder.innoway.activities.UserSettingActivity;
import io.zcoder.innoway.commons.Constants;
import io.zcoder.innoway.commons.PrefUtils;
import io.zcoder.innoway.models.Profile;
import io.zcoder.innoway.models.ProfileDetailResponse;
import io.zcoder.innoway.models.ResponseBase;
import io.zcoder.innoway.rest.RestClient;
import io.zcoder.innoway.widgets.TextViewCustom;
import retrofit.Callback;
import retrofit.RetrofitError;
import retrofit.client.Response;
import retrofit.mime.TypedFile;

public class MeFragment extends BaseFragment {

    public static final int REQUEST_EDIT_INFO = 11;
    public static final int REQUEST_CHANGE_PASSCODE = 12;
    public static final int TURN_OFF_PASSCODE = 13;
    private static final int PICK_IMAGE = 123;

    @BindView(R.id.change_passcode)
    LinearLayout mLayoutChangePasscode;
    @BindView(R.id.avatar)
    CircleImageView mAvatar;
    @BindView(R.id.common_setting)
    ImageView mSetting;
    @BindView(R.id.common_edit)
    ImageView mEdit;
    @BindView(R.id.common_title)
    TextViewCustom mTitle;
    @BindView(R.id.weight_unit)
    TextViewCustom mWeightUnit;
    @BindView(R.id.name)
    TextViewCustom mName;
    @BindView(R.id.turn_on_passcode)
    TextViewCustom mTurnOnPassCode;

    @OnClick(R.id.img_camera)
    void getImage() {
        Intent getIntent = new Intent(Intent.ACTION_GET_CONTENT);
        getIntent.setType("image/*");

        Intent pickIntent = new Intent(Intent.ACTION_PICK, android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
        pickIntent.setType("image/*");

        Intent pickIntentCamera = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
        pickIntent.setType("image/*");

        Intent chooserIntent = Intent.createChooser(getIntent, "Select Image");
        chooserIntent.putExtra(Intent.EXTRA_INITIAL_INTENTS, new Intent[]{pickIntent, pickIntentCamera});

        startActivityForResult(chooserIntent, PICK_IMAGE);
    }

    @OnClick(R.id.layout_turn_on_passcode)
    void turnOnPassCode() {
        if (mProfile == null) {
            return;
        }
        Intent intent = new Intent(getActivity(), InputPassCodeActivity.class);
        if (Utils.isBlank(mProfile.getPasscode())) {
            startActivityForResult(intent, REQUEST_CHANGE_PASSCODE);
        } else {
            intent.putExtra(Constants.CONFIRM_PASS_CODE_EXTRAS, mProfile.getPasscode());
            startActivityForResult(intent, TURN_OFF_PASSCODE);
        }
    }

    @OnClick(R.id.change_passcode)
    void changePasscode() {
        Intent intent = new Intent(getActivity(), InputPassCodeActivity.class);
        intent.putExtra(Constants.PASS_CODE_EXTRAS, mProfile.getPasscode());
        startActivityForResult(intent, REQUEST_CHANGE_PASSCODE);
    }

    @OnClick(R.id.common_setting)
    void onSetting() {
        if (mProfile == null) {
            return;
        }
        Intent intent = new Intent(getActivity(), UserSettingActivity.class);
        intent.putExtra(Constants.IS_MAIN_PROFILE_EXTRAS, mProfile.getRelation() == 0);
        startActivity(intent);
    }

    @OnClick(R.id.common_edit)
    void onEdit() {
        if (mProfile == null) {
            return;
        }
        Intent intent = new Intent(getActivity(), EditInformationActivity.class);
        intent.putExtra(Constants.PROFILE_EXTRAS, mProfile);
        startActivity(intent);
    }

    @OnClick(R.id.layout_family)
    void onFamily() {
        startActivity(new Intent(getActivity(), FamilyMembersActivity.class));
    }

    @OnClick(R.id.layout_weight_unit)
    void selectUnit() {
        if (mProfile == null) {
            return;
        }
        MaterialDialog builder = new MaterialDialog.Builder(getActivity())
                .title(R.string.weight_unit)
                .items(R.array.select_unit_weight)
                .itemsCallbackSingleChoice(-1, new MaterialDialog.ListCallbackSingleChoice() {
                    @Override
                    public boolean onSelection(MaterialDialog dialog, View view, int which, CharSequence text) {
                        saveWeightUnit(which);
                        return true;
                    }
                })
                .negativeText(R.string.cancel).build();
        builder.setSelectedIndex(mProfile.getWeight_unit());
        builder.show();
    }

    @OnClick(R.id.reminder_setting)
    void settingReminder() {
        startActivity(new Intent(getActivity(), ReminderActivity.class));
    }

    private Profile mProfile;

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.layout_me_fragment, container, false);
        ButterKnife.bind(this, view);

        setViews();

        return view;
    }

    private void setViews() {
        mSetting.setVisibility(View.VISIBLE);
        mEdit.setVisibility(View.VISIBLE);
        mTitle.setText(getString(R.string.me));
        RestClient.build(getActivity(), true).getProfile(PrefUtils.getInt(getActivity(), PrefUtils.PREF_PROFILE_ID), new Callback<ProfileDetailResponse>() {
            @Override
            public void success(ProfileDetailResponse profileDetailResponse, Response response) {
                if (profileDetailResponse.getStatus_code() != 200) {
                    showAlert(getString(R.string.error), profileDetailResponse.getMessage());
                } else {
                    mProfile = profileDetailResponse.getData();
                    if (mProfile != null) {
                        fillData();

                    }
                }
            }

            @Override
            public void failure(RetrofitError error) {
            }
        });
    }

    private void fillData() {
        mWeightUnit.setText(Utils.getUnitWeightHeight(mProfile.getWeight_unit()));
        if (!Utils.isBlank(mProfile.getAvatar_url())) {
            Picasso.with(getActivity()).load(mProfile.getAvatar_url()).into(mAvatar);
        }
        mName.setText(mProfile.getFirst_name() + " " + mProfile.getLast_name());
        if (!Utils.isBlank(mProfile.getPasscode())) {
            mLayoutChangePasscode.setVisibility(View.VISIBLE);
            mTurnOnPassCode.setText(getString(R.string.turn_off_passcode));
        } else {
            mLayoutChangePasscode.setVisibility(View.GONE);
            mTurnOnPassCode.setText(getString(R.string.turn_on_passcode));
        }
    }

    private void saveWeightUnit(final int unit) {
        showProgress();
        RestClient.build(getActivity(), true).saveWeightUnit(PrefUtils.getInt(getActivity(), PrefUtils.PREF_PROFILE_ID), unit, new Callback<ResponseBase>() {
            @Override
            public void success(ResponseBase responseBase, Response response) {
                hideProgress();
                if (responseBase.getStatus_code() == 200) {
                    mWeightUnit.setText(Utils.getUnitWeightHeight(unit));
                    setViews();
                } else {
                    showAlert(getString(R.string.error), responseBase.getMessage());
                }
            }

            @Override
            public void failure(RetrofitError error) {
                hideProgress();
            }
        });
    }

    @Override
    public void onResume() {
        super.onResume();
        setViews();
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == REQUEST_CHANGE_PASSCODE && resultCode == InputPassCodeActivity.RESPONSE_SET_PASS_CODE) {
            String pass = data.getStringExtra(Constants.PASS_CODE_EXTRAS);
            if (!Utils.isBlank(pass)) {
                setPassCode(pass);
            }
        }
        if (requestCode == TURN_OFF_PASSCODE && resultCode == InputPassCodeActivity.RESPONSE_CONFIRM_PASS_CODE) {
            boolean pass = data.getBooleanExtra(Constants.CONFIRM_PASS_CODE_EXTRAS, false);
            if (pass) {
                setPassCode("");
            }
        }
        if (requestCode == PICK_IMAGE && resultCode == Activity.RESULT_OK) {
            try {
                Bitmap photo = (Bitmap) data.getExtras().get("data");
                updateAvatar(photo);
            } catch (Exception e) {
                Uri selectedImage = data.getData();
                Bitmap b = BitmapFactory.decodeFile(new File(getRealPathFromURI(selectedImage)).getAbsolutePath());
                updateAvatar(b);
            }
        }
    }

    private void updateAvatar(Bitmap b) {
        TypedFile file = new TypedFile("multipart/form-data", resize(b));
        showProgress();
        RestClient.build(getActivity(), true).uploadAvatar(PrefUtils.getInt(getActivity(), PrefUtils.PREF_PROFILE_ID), file, new Callback<ResponseBase>() {
            @Override
            public void success(ResponseBase responseBase, Response response) {
                hideProgress();
                if (responseBase.getStatus_code() != 200) {
                    showAlert(getString(R.string.error), responseBase.getMessage());
                } else {
                    setViews();
                }
            }

            @Override
            public void failure(RetrofitError error) {
                hideProgress();
            }
        });
    }

    private File resize(Bitmap b) {
        File dir = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DCIM);
        Bitmap out = getResizedBitmap(b, 600, 600);

        File file = new File(dir, Calendar.getInstance().getTimeInMillis() + ".jpg");
        FileOutputStream fOut;
        try {
            fOut = new FileOutputStream(file);
            out.compress(Bitmap.CompressFormat.PNG, 100, fOut);
            fOut.flush();
            fOut.close();
            b.recycle();
            out.recycle();
        } catch (Exception e) {
        }
        return file;
    }

    public Bitmap getResizedBitmap(Bitmap bm, int newHeight, int newWidth) {
        int width = bm.getWidth();
        int height = bm.getHeight();
        float scaleWidth = ((float) newWidth) / width;
        float scaleHeight = ((float) newHeight) / height;

        Matrix matrix = new Matrix();

        matrix.postScale(scaleWidth, scaleHeight);

        Bitmap resizedBitmap = Bitmap.createBitmap(bm, 0, 0, width, height, matrix, false);
        return resizedBitmap;

    }

    private String getRealPathFromURI(Uri contentURI) {
        String result = "";
        try {
            Cursor cursor = getActivity().getContentResolver().query(contentURI, null, null, null, null);
            if (cursor == null) {
                result = contentURI.getPath();
            } else {
                cursor.moveToFirst();
                int idx = cursor.getColumnIndex(MediaStore.Images.ImageColumns.DATA);
                result = cursor.getString(idx);
                cursor.close();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return result;
    }

    private void setPassCode(String pass) {
        RestClient.build(getActivity(), true).setPasscode(PrefUtils.getInt(getActivity(), PrefUtils.PREF_PROFILE_ID), pass, new Callback<ResponseBase>() {
            @Override
            public void success(ResponseBase responseBase, Response response) {
                if (responseBase.getStatus_code() != 200) {
                    showAlert(getString(R.string.error), responseBase.getMessage());
                } else {
                    setViews();
                }
            }

            @Override
            public void failure(RetrofitError error) {

            }
        });
    }
}
